import { Form, Input, Button, Select, Radio, Checkbox, message, Row, Col, Result } from '@/utils/antd-imports';
import { useState, useRef, useEffect } from 'react';



import DatePicker from 'antd/es/date-picker';






import dayjs from 'dayjs';
import './css/Questionnaire.css';
import employeeApi from '../api/employeeApi';
import { sanitizeFormData, validateIdCard, validatePhone, validateEmail, containsDangerousSQL, RateLimiter } from '../utils/security';

const { Option } = Select;
const { TextArea } = Input;

const Questionnaire = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [submitSuccess, setSubmitSuccess] = useState(false);
  
  // 速率限制器（防止频繁提交）
  const rateLimiter = useRef(new RateLimiter(3, 60000)); // 60秒内最多3次提交
  const clientId = useRef(null);
  
  // 生成客户端标识
  useEffect(() => {
    if (!clientId.current) {
      clientId.current = `client_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    }
  }, []);

  const onFinish = async (values) => {
    setLoading(true);
    try {
      // 🔒 安全措施1: 速率限制检查
      if (!rateLimiter.current.check(clientId.current)) {
        message.error('提交过于频繁，请稍后再试');
        setLoading(false);
        return;
      }

      // 🔒 安全措施2: 验证数据格式
      if (!values.name || values.name.trim().length < 2 || values.name.trim().length > 50) {
        message.error('姓名长度必须在2-50个字符之间');
        setLoading(false);
        return;
      }

      if (values.idCard && !validateIdCard(values.idCard)) {
        message.error('身份证号格式不正确');
        setLoading(false);
        return;
      }

      if (!validatePhone(values.phone)) {
        message.error('手机号码格式不正确');
        setLoading(false);
        return;
      }

      if (values.email && !validateEmail(values.email)) {
        message.error('邮箱格式不正确');
        setLoading(false);
        return;
      }

      if (values.emergencyPhone && !validatePhone(values.emergencyPhone)) {
        message.error('紧急联系人手机号码格式不正确');
        setLoading(false);
        return;
      }

      // 🔒 安全措施3: 检查是否包含危险的SQL关键字
      const checkFields = [
        'name', 'hometown', 'ethnicity', 'registeredAddress', 'currentAddress',
        'major', 'school', 'emergencyContact', 'bankCardNumber', 'bankName', 'certificates'
      ];
      
      for (const field of checkFields) {
        if (values[field] && containsDangerousSQL(values[field])) {
          message.error('输入包含非法字符，请重新填写');
          setLoading(false);
          return;
        }
      }

      console.log('Received values:', values);
      
      // 🔒 安全措施4: 清理输入数据
      const sanitizedValues = sanitizeFormData(values);
      
      // 转换表单数据格式以匹配API要求（使用清理后的数据）
      const employeeData = {
        employeeType: sanitizedValues.employeeType === 'full-time' ? '正式' : 
                     sanitizedValues.employeeType === 'intern' ? '实习' : '见习',
        name: sanitizedValues.name,
        gender: sanitizedValues.gender === 'male' ? '男' : '女',
        maritalStatus: sanitizedValues.maritalStatus === 'married' ? '已婚' : '未婚',
        nativePlace: sanitizedValues.hometown,
        politicalStatus: sanitizedValues.politicalStatus === 'party-member' ? '党员' :
                        sanitizedValues.politicalStatus === 'league-member' ? '团员' :
                        sanitizedValues.politicalStatus === 'masses' ? '群众' : '其他民主党派',
        birthday: sanitizedValues.birthDate ? dayjs(sanitizedValues.birthDate).format('YYYY-MM-DD') : null,
        idCard: sanitizedValues.idCard,
        registeredAddress: sanitizedValues.registeredAddress,
        phone: sanitizedValues.phone,
        wechat: sanitizedValues.wechat,
        email: sanitizedValues.email,
        education: sanitizedValues.education === 'high-school' ? '高中' :
                  sanitizedValues.education === 'college' ? '大专' :
                  sanitizedValues.education === 'bachelor' ? '本科' :
                  sanitizedValues.education === 'master' ? '硕士' : '博士',
        major: sanitizedValues.major,
        university: sanitizedValues.school, // 添加毕业院校字段
        graduationDate: sanitizedValues.graduationDate ? dayjs(sanitizedValues.graduationDate).format('YYYY-MM-DD') : null,
        emergencyContact: sanitizedValues.emergencyContact,
        emergencyPhone: sanitizedValues.emergencyPhone,
        ethnicity: sanitizedValues.ethnicity || '汉族',
        skillCertificates: sanitizedValues.certificates || '',
        remarks: '通过入职信息表提交'
      };
      
      // 只在有值时才添加银行信息和现居住地址字段
      if (sanitizedValues.bankCardNumber) {
        employeeData.bankAccount = sanitizedValues.bankCardNumber;
      }
      if (sanitizedValues.bankName) {
        employeeData.bankName = sanitizedValues.bankName;
      }
      if (sanitizedValues.currentAddress) {
        employeeData.currentAddress = sanitizedValues.currentAddress;
      }

      // 调用新增员工API（使用公开接口）
      console.log('发送员工数据:', employeeData);
      
      try {
        const response = await employeeApi.submitQuestionnaire(employeeData);
        console.log('API响应:', response);
        
        // 只要能到达这里，说明请求成功了
        // 设置成功状态，显示成功页面
        setSubmitSuccess(true);
      } catch (error) {
        // 检查HTTP响应状态码
        const httpStatus = error.response?.status || error.response?.statusCode;
        
        // 如果HTTP状态码是2xx，说明请求到了服务器且被处理了
        // 即使业务code不是200，数据也可能已保存
        if (httpStatus >= 200 && httpStatus < 300) {
          // 假设数据已保存，显示成功页面
          setSubmitSuccess(true);
          return;
        }
        
        // 重新抛出错误，让外层catch处理
        throw error;
      }
    } catch (error) {
      console.error('提交失败:', error);
      
      // 提供更详细的错误信息
      let errorMessage = '提交失败，请重试';
      
      if (error.code) {
        // 业务错误
        errorMessage = `提交失败: ${error.message || '服务器返回错误'}`;
        if (error.code === 400) {
          errorMessage = '数据格式错误，请检查填写的信息';
        } else if (error.code === 409) {
          errorMessage = '员工信息已存在，请检查身份证号或手机号';
        } else if (error.code === 500) {
          errorMessage = '服务器内部错误，请稍后重试';
        }
      } else if (error.response) {
        // HTTP 错误
        const status = error.response.status;
        if (status === 400) {
          errorMessage = '请求参数错误，请检查填写的信息';
        } else if (status === 401) {
          errorMessage = '登录已过期，请重新登录';
        } else if (status === 403) {
          errorMessage = '权限不足，无法提交';
        } else if (status === 404) {
          errorMessage = '接口不存在，请联系管理员';
        } else if (status === 500) {
          errorMessage = '服务器内部错误，请稍后重试';
        } else {
          errorMessage = `网络错误 (${status})，请稍后重试`;
        }
      } else if (error.message) {
        // 其他错误
        errorMessage = `提交失败: ${error.message}`;
      }
      
      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 如果提交成功，显示成功页面
  if (submitSuccess) {
    return (
      <div className="questionnaire-container">
        <div className="questionnaire-card">
          <Result
            status="success"
            title="提交成功"
            subTitle="我们已经收到您的个人信息，感谢您的加入"
          />
        </div>
      </div>
    );
  }

  return (
    <div className="questionnaire-container">
      <div className="questionnaire-card">
        <Row justify="center" className="header-section">
          <Col>
            <h1 className="form-title">凯泽利员工入职信息表</h1>
          </Col>
        </Row>
        
        <p className="form-description">
          请如实填写以下信息，我们将严格保密您的个人信息
        </p>
        
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          autoComplete="off"
        >
          {/* 基本信息部分 */}
          <h2 className="form-section-title">基本信息</h2>
          
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                label="员工类型"
                name="employeeType"
                rules={[{ required: true, message: '请选择员工类型' }]}
              >
                <Radio.Group>
                  <Radio value="full-time">正式员工</Radio>
                  <Radio value="intern">实习生</Radio>
                  <Radio value="trainee">见习生</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                label="姓名"
                name="name"
                rules={[{ required: true, message: '请输入您的姓名' }]}
              >
                <Input placeholder="请输入您的姓名" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                label="性别"
                name="gender"
                rules={[{ required: true, message: '请选择您的性别' }]}
              >
                <Radio.Group>
                  <Radio value="male">男</Radio>
                  <Radio value="female">女</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                label="婚姻状况"
                name="maritalStatus"
                rules={[{ required: true, message: '请选择婚姻状况' }]}
              >
                <Radio.Group>
                  <Radio value="married">已婚</Radio>
                  <Radio value="unmarried">未婚</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                label="籍贯"
                name="hometown"
                rules={[{ required: true, message: '请输入您的籍贯' }]}
              >
                <Input placeholder="请输入您的籍贯" />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                label="民族"
                name="ethnicity"
                rules={[{ required: true, message: '请输入您的民族' }]}
              >
                <Input placeholder="请输入您的民族" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                label="政治面貌"
                name="politicalStatus"
                rules={[{ required: true, message: '请选择政治面貌' }]}
              >
                <Select placeholder="请选择政治面貌">
                  <Option value="party-member">中共党员</Option>
                  <Option value="league-member">共青团员</Option>
                  <Option value="masses">群众</Option>
                  <Option value="other">其他民主党派</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                label="生日"
                name="birthDate"
                rules={[{ required: true, message: '请选择您的出生日期' }]}
              >
                <DatePicker 
                  className="full-width-datepicker"
                  disabledDate={(current) => current && current > dayjs().endOf('day')}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="身份证号"
            name="idCard"
            rules={[
              { required: true, message: '请输入您的身份证号' },
              { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}[0-9Xx]$/, 
                message: '请输入正确的身份证号码' }
            ]}
          >
            <Input placeholder="请输入您的身份证号码" />
          </Form.Item>

          <Form.Item
            label="户籍地址"
            name="registeredAddress"
            rules={[{ required: true, message: '请输入您的户籍地址' }]}
          >
            <Input placeholder="请输入您的户籍地址" />
          </Form.Item>

          <Form.Item
            label="现居住地址"
            name="currentAddress"
          >
            <Input placeholder="请输入您现居住地址" />
          </Form.Item>

          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                label="联系电话"
                name="phone"
                rules={[
                  { required: true, message: '请输入您的联系电话' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
                ]}
              >
                <Input placeholder="请输入您的手机号码" />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                label="微信"
                name="wechat"
                rules={[{ required: true, message: '请输入您的微信号' }]}
              >
                <Input placeholder="请输入您的微信号" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="电子邮箱"
            name="email"
            rules={[
              { required: true, message: '请输入您的电子邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input placeholder="请输入您的电子邮箱" />
          </Form.Item>

          {/* 教育背景部分 */}
          <h2 className="form-section-title">教育背景</h2>
          
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                label="学历/学位"
                name="education"
                rules={[{ required: true, message: '请选择您的学历/学位' }]}
              >
                <Select placeholder="请选择您的学历/学位">
                  <Option value="high-school">高中</Option>
                  <Option value="college">大专</Option>
                  <Option value="bachelor">本科</Option>
                  <Option value="master">硕士</Option>
                  <Option value="phd">博士</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                label="所学专业"
                name="major"
                rules={[{ required: true, message: '请输入您的专业' }]}
              >
                <Input placeholder="请输入您的专业" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                label="毕业院校"
                name="school"
                rules={[{ required: true, message: '请输入您的毕业院校' }]}
              >
                <Input placeholder="请输入您的毕业院校" />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                label="毕业时间"
                name="graduationDate"
                rules={[{ required: true, message: '请选择毕业时间' }]}
              >
                <DatePicker className="full-width-datepicker" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="技能证书"
            name="certificates"
          >
            <TextArea rows={2} placeholder="请输入您获得的技能证书（如无请留空）" />
          </Form.Item>

          {/* 紧急联系人部分 */}
          <h2 className="form-section-title">紧急联系人</h2>
          
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                label="紧急联系人姓名"
                name="emergencyContact"
                rules={[{ required: true, message: '请输入紧急联系人姓名' }]}
              >
                <Input placeholder="请输入紧急联系人姓名" />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                label="紧急联系电话"
                name="emergencyPhone"
                rules={[
                  { required: true, message: '请输入紧急联系电话' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
                ]}
              >
                <Input placeholder="请输入紧急联系电话" />
              </Form.Item>
            </Col>
          </Row>

          {/* 银行信息部分 */}
          <h2 className="form-section-title">银行信息（非必填）</h2>
          
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                label="银行卡号"
                name="bankCardNumber"
              >
                <Input placeholder="请输入您的银行卡号" />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                label="开户行"
                name="bankName"
              >
                <Input placeholder="请输入开户行名称" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="agreement"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) =>
                  value ? Promise.resolve() : Promise.reject(new Error('请阅读并同意协议')),
              },
            ]}
          >
            <Checkbox className="agreement-checkbox">
              我已阅读并同意<a href="#" className="agreement-link">《个人信息保护协议》</a>
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading} 
              block 
              size="large"
              className="submit-button"
            >
              提交信息
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Questionnaire;